package com.mooc.yohoshop.ui.seckill;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class TimeService extends Service {

    public long time = 0l;
    private TimeThread timeThread;
     UIUpdateInterface uiUpdateInterface;

    public void setUiUpdateInterface(UIUpdateInterface uiUpdateInterface) {
        this.uiUpdateInterface = uiUpdateInterface;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        timeThread = new TimeThread(new TimeHander(this));
        timeThread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new TimeBinder();
    }

    public interface UIUpdateInterface{
        void timeCallBack(long time);
    }

   public class TimeBinder extends Binder {

        public TimeService getService() {
            return TimeService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timeThread.interrupt();
    }

    static class TimeThread extends Thread{

        private TimeHander hander;

        public TimeThread(TimeHander hander){
            this.hander = hander;
        }

        @Override
        public void run() {
            super.run();
            while (!interrupted()){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                hander.sendEmptyMessage(0);
            }
        }
    }

    static class TimeHander extends Handler{

        private WeakReference<TimeService>weakReference;

        public TimeHander(TimeService service){
            weakReference = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (weakReference.get()==null)
                return;
            weakReference.get().time+=1;
            if (weakReference.get().uiUpdateInterface!=null)
                weakReference.get().uiUpdateInterface.timeCallBack(weakReference.get().time);
        }
    }

}
